package hadoop.mr06;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class Counter_mapper extends Mapper<LongWritable, Text,Text, IntWritable> {
    private Text t1 = new Text();
    private IntWritable L1 = new IntWritable();

    // todo 从程序的上下文环境中获取一个全剧计数器，并制定计数器所属组别和计数器的名字
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
//      创建计数器 context.getCounter(自定义计数器所属组别,自定义计数器名字)
        Counter counter = context.getCounter("errWordCounter", "mysql counter");

        String line = value.toString();
        String[] words = line.split("\\s+");
        for (String word : words) {
            // 使用计数器，检测mysql出现的次数
            if(word.equals("mysql")){
                counter.increment(1);
            }

            t1.set(word);
            L1.set(1);
            context.write(t1, L1);
        }
    }
}
